<template>
    <div 
        ref="sliderContainer" 
        @mousemove="onMouseMove" 
        @mouseup="onMouseUp" 
        @mouseleave="onMouseLeave" 
        class="slider-verify-container"
    >
        <span v-if="blockState === 0">请按住滑块，拖动到最右边</span>
        <div 
            @mousedown="onMouseDown" 
            :style="{width: leftP}" 
            class="slider-verify-block"
        ></div>
        <div 
            :style="{width: leftP}" 
            class="slider-verify-complete"
        >
            <span v-if="blockState === 2">验证成功</span>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
const emits = defineEmits(['success', 'failed'])
const leftP = ref('0')
const blockState = ref(0)
const startP = ref(undefined)
const sliderContainer = ref(undefined)

// 鼠标按下
const onMouseDown = (e) => {
    if(blockState.value !== 2){
        leftP.value  = '0'
        blockState.value = 1
        startP.value = {
            clientX : e.clientX
        }
    }else{
        leftP.value  = '0'
        blockState.value = 0
    }
}

// 鼠标移动
const onMouseMove = (e) => {
    if(blockState.value === 1){
        let width = e.clientX - startP.value.clientX
        if(width + 56 > 400){
            leftP.value = 400 - 56 + 'px'
            blockState.value = 2
            emits('success')
        }else{
            leftP.value = width + 'px'

        }
    }
}

// 鼠标释放
const onMouseUp = (e) => {
    if(blockState.value !== 2){
        leftP.value  = "0"
        blockState.value = 0
        emits('failed')
    }
}

// 鼠标离开
const onMouseLeave = (e) => {
    if(blockState.value !== 2){
        leftP.value  = "0"
        blockState.value = 0
        emits('failed')
    }
}
</script>

<style scoped lang="scss">
.slider-verify-container{
    width: 100%;
    height: 56px;
    background-color: transparent;
    position: relative;
    border: 1px solid #20cccf;
    text-align: center;
    color: #20cccf;
    line-height: 56px;
    user-select: none;
}
.slider-verify-complete{
    width: 0;
    height: 56px;
    position: absolute;
    background-color: #00e6f14f;
    left: 0;
    top: 0;
}
.slider-verify-block{
    width: 56px;
    height: 56px;
    background-color: #ccc;
    position: absolute;
    left: 0;
    top: -1px;
    border: 1px solid #20cccf;
}
</style>